package com.ruoyi.web.controller.machine;

import com.ruoyi.agent.domain.KwMachineAgent;
import com.ruoyi.agent.service.IKwMachineAgentService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HostConstant;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.jsch.JschAuth;
import com.ruoyi.common.utils.jsch.JschResult;
import com.ruoyi.common.utils.jsch.JschUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.credential.domain.KwCredentialAccess;
import com.ruoyi.credential.domain.KwUserCredential;
import com.ruoyi.credential.service.IKwCredentialAccessService;
import com.ruoyi.credential.service.IKwUserCredentialService;
import com.ruoyi.machine.domain.KwMachineInfo;
import com.ruoyi.machine.service.IKwMachineInfoService;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 主机信息Controller
 * 
 * @author gonianer
 * @date 2023-11-14
 */
@RestController
@RequestMapping("/machine/machine")
public class KwMachineInfoController extends BaseController
{
    @Autowired
    private IKwMachineInfoService kwMachineInfoService;
    @Autowired
    private IKwCredentialAccessService kwCredentialAccessService;
    @Autowired
    private IKwUserCredentialService kwUserCredentialService;
    @Autowired
    private IKwMachineAgentService kwMachineAgentService;
    @Autowired
    private ISysJobService jobService;

    /**
     * 查询主机信息列表
     */
    @PreAuthorize("@ss.hasPermi('machine:machine:list')")
    @GetMapping("/list")
    public TableDataInfo list(KwMachineInfo kwMachineInfo)
    {
        startPage();
        List<KwMachineInfo> list = kwMachineInfoService.selectKwMachineInfoList(kwMachineInfo);
        return getDataTable(list);
    }

    /**
     * 导出主机信息列表
     */
    @PreAuthorize("@ss.hasPermi('machine:machine:export')")
    @Log(title = "主机信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KwMachineInfo kwMachineInfo)
    {
        List<KwMachineInfo> list = kwMachineInfoService.selectKwMachineInfoList(kwMachineInfo);
        ExcelUtil<KwMachineInfo> util = new ExcelUtil<KwMachineInfo>(KwMachineInfo.class);
        util.exportExcel(response, list, "主机信息数据");
    }

    /**
     * 获取主机信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('machine:machine:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        KwMachineInfo kwMachineInfo = kwMachineInfoService.selectKwMachineInfoById(id);
        KwCredentialAccess access = new KwCredentialAccess();
        access.setUserId(this.getUserId());
        access.setTargetId(kwMachineInfo.getId());
        List<KwCredentialAccess> accesses = kwCredentialAccessService.selectKwCredentialAccessList(access);
        if(accesses!=null && accesses.size()>0){
            kwMachineInfo.setCredentialId(accesses.get(0).getCredentialId());
        }
        KwMachineAgent agent = new KwMachineAgent();
        agent.setMachineId(id);
        List<KwMachineAgent> agents = kwMachineAgentService.selectKwMachineAgentList(agent);
        if(!CollectionUtils.isEmpty(agents)){
            kwMachineInfo.setAgent(agents.get(0));
        }
        return success(kwMachineInfo);
    }

    /**
     * 新增主机信息
     */
    @PreAuthorize("@ss.hasPermi('machine:machine:add')")
    @Log(title = "主机信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KwMachineInfo kwMachineInfo) throws Exception
    {

        KwUserCredential credential = kwUserCredentialService.selectKwUserPasswdById(kwMachineInfo.getCredentialId());
        if(credential == null){
            throw new ServiceException("用户凭证不能为空");
        }
        //验证机器ssh连接
        JschAuth jschAuth = new JschAuth(kwMachineInfo.getIp(),kwMachineInfo.getSshPort(),credential.getUsername(),credential.getSecret());
        JschUtil.testConnect(jschAuth);
        //验证jwagent端口号
        String agentPort = kwMachineInfo.getAgent().getPort();
        JschResult result = JschUtil.execShell(jschAuth, JschUtil.COMMAND_CHECK_PORT_USED+agentPort);
        if(result.getExitStatus()==0){
            throw new ServiceException("机器端口："+agentPort+"已被占用，请检查机器端口或在高级配置中重新配置。");
        }
        kwMachineInfo.setStatus(HostConstant.STATUS_SUBMIT);
        kwMachineInfo.setCreateUser(String.valueOf(this.getUserId()));
        kwMachineInfo.setUpdateUser(String.valueOf(this.getUserId()));
        int rows = kwMachineInfoService.insertKwMachineInfo(kwMachineInfo);
        if(rows>0){
           KwCredentialAccess access = new KwCredentialAccess();
           access.setUserId(this.getUserId());
           access.setCredentialId(kwMachineInfo.getCredentialId());
           access.setTargetId(kwMachineInfo.getId());
           kwCredentialAccessService.insertKwCredentialAccess(access);
        }
        //添加jwagent信息
        KwMachineAgent agent = kwMachineInfo.getAgent();
        agent.setMachineId(kwMachineInfo.getId());
        agent.setUsername(credential.getUsername());
        kwMachineAgentService.insertKwMachineAgent(agent);
        //启动添加主机任务
        SysJob job = new SysJob();
        job.setJobId(kwMachineInfo.getId());
        job.setJobName("addHost");
        job.setJobGroup("sys");
        job.setInvokeTarget("hostTask.addHost("+kwMachineInfo.getId()+"L)");
        job.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
        job.setConcurrent(ScheduleConstants.CONCURRENT_NO);
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        job.setCreateBy(getUsername());
        jobService.runOnce(job);

        return toAjax(rows);
    }

    /**
     * 修改主机信息
     */
    @PreAuthorize("@ss.hasPermi('machine:machine:edit')")
    @Log(title = "主机信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KwMachineInfo kwMachineInfo)
    {
        KwUserCredential credential = kwUserCredentialService.selectKwUserPasswdById(kwMachineInfo.getCredentialId());
        if(credential == null){
            new ServiceException("用户凭证不能为空");
        }
        //验证机器ssh连接
        JschAuth jschAuth = new JschAuth(kwMachineInfo.getIp(),kwMachineInfo.getSshPort(),credential.getUsername(),credential.getSecret());
        JschUtil.testConnect(jschAuth);
        kwMachineInfo.setUpdateUser(String.valueOf(this.getUserId()));
        int rows = kwMachineInfoService.updateKwMachineInfo(kwMachineInfo);
        if(rows>0 && kwMachineInfo.getCredentialId()!=null){
            KwCredentialAccess access = new KwCredentialAccess();
            access.setUserId(this.getUserId());
            access.setTargetId(kwMachineInfo.getId());
            List<KwCredentialAccess> accesses = kwCredentialAccessService.selectKwCredentialAccessList(access);
            if(accesses!=null && accesses.size()>0){
                access = accesses.get(0);
                access.setCredentialId(kwMachineInfo.getCredentialId());
                kwCredentialAccessService.updateKwCredentialAccess(access);
            }else {
                access.setCredentialId(kwMachineInfo.getCredentialId());
                kwCredentialAccessService.insertKwCredentialAccess(access);
            }
        }
        return toAjax(rows);
    }

    /**
     * 删除主机信息
     */
    @PreAuthorize("@ss.hasPermi('machine:machine:remove')")
    @Log(title = "主机信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) throws Exception
    {
        Long machinId = ids[0];
        KwMachineInfo machineInfo = kwMachineInfoService.selectKwMachineInfoById(machinId);
        if(machineInfo==null){
            throw new ServiceException("删除主机ID="+machinId+"不存在，请刷新");
        }
        //设置主机状态为删除中
        machineInfo.setStatus(HostConstant.STATUS_DELETED);
        kwMachineInfoService.updateKwMachineInfo(machineInfo);
        //启动删除主机任务
        SysJob job = new SysJob();
        job.setJobId(machineInfo.getId());
        job.setJobName("addHost");
        job.setJobGroup("sys");
        job.setInvokeTarget("hostTask.delHost("+machineInfo.getId()+"L)");
        job.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
        job.setConcurrent(ScheduleConstants.CONCURRENT_NO);
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        job.setCreateBy(getUsername());
        jobService.runOnce(job);
        return AjaxResult.success();
    }
}
